#! /usr/bin/env python
# -*- coding: utf-8 tabstop: 2 -*-
#
# railease.py - Simple script to view TV streams from rai.tv
#
# Copyright © 2010 Stefano Sanfilippo
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Authors:
# 	Stefano Sanfilippo

import sys
import re
import base64
import httplib2

http     = httplib2.Http()
baseurl  = 'http://mediapolis.rai.it/relinker/relinkerServlet.htm?cont=%s'
channels = { 'Rai4'       : '75708',
             'RaiNews'    : '1',
             'RaiGulp'    : '4119',
             'RaiSport1'  : '4145',
             'RaiScuola'  : '24268',
             'RaiStoria'  : '24269',
             'RaiExtra'   : '72382',
             'RaiPremium' : '72383',
             'RaiYoYo'    : '72384',
             'RaiMovie'   : '72381',
             'RaiMed'     : '87127',
             'EuroNews'   : '113784' }

class StreamError(Exception): pass

def date():
	headers, now = http.request('http://videowall.rai.it/cgi-bin/date', 'GET')
	return now

def gettoken(channel, now):
	datepattern = '^(\d*)-(\d*)-(\d*)\s(\d*):(\d*):(\d*)'
	tokenmodel  = '%s;%s;%s-%s-512-%s-%s-%s-500'
	date = re.match(datepattern, now).groups()
	day, month, year, hour, minutes, seconds = date
	return tokenmodel % (year, channel, day, month, hour, minutes, seconds)

def fixmediaurl(url, token): #ORRIBLEHACK
	if not re.search('relinkerServlet', url): return url
	headers = {'viaurl': 'www.rai.tv', 'ttAuth': token}
	headers, asx = http.request(url, 'POST', body='\x00', headers=headers)
	redirect = re.search('HREF="([\S ]+)"', asx)
	return redirect.group(1)

def encode(token, key='hMrxuE2T8V0WRW0VmHaKMoFwy1XRc+hK7eBX2tTLVTw='):
	newtoken = ''.join(chr(ord(ch)^1) for ch in token) + ';1'
	lenght = len(newtoken) - 1
	encoded = ''
	for i in range(lenght, -1, -1):
		enc = chr(ord(newtoken[i]) ^ ord(key[lenght - i]))
		encoded = enc + encoded
	return base64.encodestring(str.encode(encoded)).decode() 

if __name__ == '__main__':
	if len(sys.argv) > 1:		
		arg     = sys.argv[1]
		channel = 'http' in arg and raitv.channelid(arg) or channels[arg]
		url     = baseurl % channel
		date    = date()
		token   = gettoken(channel, date)
		print fixmediaurl(url, encode(token))
	else:
		print """Railease 1.1
Copyright (C) 2010 - Stefano Sanfilippo
Questo programma può essere ridistribuito liberamente sotto i termini della GNU GPL

Uso: railease.py canale

  canale = (Rai4|RaiNews|RaiGulp|RaiSport1|RaiScuola|RaiStoria|
            RaiExtra|RaiPremium|RaiYoYo|RaiMovie|RaiMed|EuroNews)"""
